import { deleteAnnex as deleteAnnexByFsId, upload, download } from '@neu/dcam-ui/api/annex'
import { getToken } from '@neu/biz-core/utils/auth'
import axios from 'axios'
export default {
  data() {
    return {
      /** 上传路径 */
      importUrl: upload,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      }
    }
  },
  methods: {
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.annex.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.annex.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      deleteAnnexByFsId(file.fsId).then(res => {
        if (res.status === 'failure') {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'error'
          })
        } else {
          this.formItem.annex.splice(this.formItem.annex.indexOf(file), 1)
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }
      })
    },
    /** 文件上传之前 */
    handleBeforeUpLoad(file) {

    },
    /** 下载附件 */
    downloadFile(tag) {
      download(tag.fsId).then(res => {
        const content = res.data
        const blob = new Blob([content])
        const fileName = tag.name
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    uploadRequest(param) {
      const that = this
      const fileObj = param.file
      const formData = new FormData()
      formData.append('file', fileObj)
      axios.post(this.importUrl, formData, { headers: this.headers }).then((response) => {
        const data = response.data.data
        const obj = {
          fsId: data.fsId,
          name: data.name
        }
        const fsIdArr = that.formItem.annex.map(t => t.fsId)
        that.formItem.annex.push(obj)
        if (fsIdArr.includes(obj.fsId)) {
          that.formItem.annex.pop()
        }
      })
    }
  }
}
